<?php
namespace app\agent\controller;
use think\Controller;
use think\request;
use think\Db;

class Login extends Controller
{
    public function index()
    {
    	// 已登录直接登录
    	if (session('agent_id')) {
            $this->redirect('agent/index/index');
        }
        return  $this->fetch();
    }
    
    
    public function dologin(){
    	 if(request()->isPost()){
    	 	$data['mobile']= $_POST['agent_mobile'];
    	 	$data['password']=md5_salt($_POST['agent_password']);
    	 	
    	 	$user1=Db::table('info_agent')->where($data)->find();
    	 	
    	 	$user2=Db::table('info_agent')
    	 				->where('password',md5_salt($_POST['agent_password']))
    	 				->where('cb_login_name',$_POST['agent_mobile'])
    	 				->find();
    	 	if($user1){
    	 		$user = $user1;
    	 	}
    	 	
    	 	if($user2){
    	 		$user = $user2;
    	 	}
    	 	
    	 	if(!empty($user)){
				if($user['status'] != 2){
	            	$status='登录成功';
	            	session('agent_id', $user['id']);
					session('agent_user_id', $user['user_id']);
					session('mobile', $user['mobile']);
					session('salesman_id', $user['salesman_id']);
					session('oem_id', $user['oem_id']);
					session('agency_id1', $user['agency_id1']);
					session('agency_id2', $user['agency_id2']);
					session('salesman_id', $user['salesman_id']);
               		session('agent_name', $user['agent_name']);
               		return json(['code'=>200,'msg'=>$status]);
				}else{
	            	$status='<span style="color:red">帐号有问题</span>';
	            	return json(['code'=>402,'msg'=>$status]);
				}
    	 	}else{
            	$status='<span style="color:red">账户名或密码错误</span>';
            	return json(['code'=>408,'msg'=>$status]);
			}
    	 	
    	 	
    	 }
    	
    	
   	}
  	
  	/**
     * 修改密码
     */
    public function return_pwd() {
    	if(request()->isPost()){
    		
    		$result = check_sendcode($_POST['mobile'], $_POST['yzm'], '发送成功');

			if($result != 1) {
				$this->error('验证码错误或过期');
			}
    		$user_info = db('info_agent')->where('mobile',$_POST['mobile'])->find();
	    	if($user_info){
	    			$pwd = md5_salt($_POST['pwd']);
	    			$result = Db::table('info_agent')->where('id', $user_info['id'])->update(['password' => $pwd]);
	    			if($result){
	    				$this->success('修改成功','agent/index/login');
	    			}else{
	    				$this->error('修改失败');
	    			}
	   		}else{
	   			$this->error('用户不存在');
	   		}
    	}
    	return  $this->fetch();
    } 
    
    
  	/**
     * 退出登录
     */
    public function logout() {
        session(null);
        $this->success('退出成功', 'agent/login/index');
    } 
}
